package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.ElementPortEth;
import com.ruoyi.net.domain.ElementPortMode;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementPortMtnPhy;
import com.ruoyi.net.service.IElementPortMtnPhyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-mtnphy接口Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-接口-mtnphy接口")
@RestController
@RequestMapping("/element/port/mtn/phy")
public class ElementPortMtnPhyController extends BaseController {
    @Autowired
    private IElementPortMtnPhyService elementPortMtnPhyService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 读取网元-接口-mtnphy接口列表
     */
    @ApiOperation(value = "读取网元-接口-mtnphy接口列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:phy:list')")
    @GetMapping("/read")
    public TableDataInfo read(ElementPortMtnPhy elementPortMtnPhy) {
        startPage();
        List<ElementPortMtnPhy> elementPortMtnPhies = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "        <type>MTN-FGPHY</type>" +
                        "        <enabled>enable</enabled>" +
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortMtnPhy.getElementId());
        if (sysConfigService.selectDebugEnabled()) {
            deviceManager.getDevice(netElement.getIp());
            String rpcReply = deviceManager.getConfig(xml.toString());

            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortMtnPhy entity = new ElementPortMtnPhy();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setTerminalName(getXmlLabelValue(node, "name"));
                    entity.setTerminalEnable(getXmlLabelValue(node, "enabled"));
//                    entity.setPortDesc(getXmlLabelValue(node, "description"));
                    Node ethOption = getXmlLabelNode(node, "eth-option");
                    Node flexeInterface = getXmlLabelNode(node, "flexe-ctrlinterface");
                    entity.setNonAccessNum(getXmlLabelValue(flexeInterface, "unavailable-timeslot-count"));
                    entity.setFecMode(getXmlLabelValue(flexeInterface, "fec-mode"));
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活

                    elementPortMtnPhies.add(entity);
                }
            }
        }
        startPage();
        return getDIYPageTable(elementPortMtnPhies);
    }

    /**
     * 查询网元-接口-mtnphy接口列表
     */
    @ApiOperation(value = "查询网元-接口-mtnphy接口列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:phy:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementPortMtnPhy elementPortMtnPhy) {
        startPage();
        List<ElementPortMtnPhy> list = elementPortMtnPhyService.selectElementPortMtnPhyList(elementPortMtnPhy);
        return getDataTable(list);
    }

    /**
     * 导出网元-接口-mtnphy接口列表
     */
    @ApiOperation(value = "导出网元-接口-mtnphy接口列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:phy:export')")
    @Log(title = "网元-接口-mtnphy接口", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementPortMtnPhy elementPortMtnPhy) {
        List<ElementPortMtnPhy> list = elementPortMtnPhyService.selectElementPortMtnPhyList(elementPortMtnPhy);
        ExcelUtil<ElementPortMtnPhy> util = new ExcelUtil<ElementPortMtnPhy>(ElementPortMtnPhy.class);
        util.exportExcel(response, list, "网元-接口-mtnphy接口数据");
    }

    /**
     * 获取网元-接口-mtnphy接口详细信息
     */
    @ApiOperation(value = "获取网元-接口-mtnphy接口详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:phy:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementPortMtnPhyService.selectElementPortMtnPhyById(id));
    }

    /**
     * 新增网元-接口-mtnphy接口
     */
    @ApiOperation(value = "新增网元-接口-mtnphy接口", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:phy:add')")
    @Log(title = "网元-接口-mtnphy接口", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementPortMtnPhy elementPortMtnPhy) {
        return toAjax(elementPortMtnPhyService.insertElementPortMtnPhy(elementPortMtnPhy));
    }

    /**
     * 修改网元-接口-mtnphy接口
     */
    @ApiOperation(value = "修改网元-接口-mtnphy接口", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:phy:edit')")
    @Log(title = "网元-接口-mtnphy接口", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementPortMtnPhy elementPortMtnPhy) {
        return toAjax(elementPortMtnPhyService.updateElementPortMtnPhy(elementPortMtnPhy));
    }

    /**
     * 删除网元-接口-mtnphy接口
     */
    @ApiOperation(value = "删除网元-接口-mtnphy接口", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:phy:remove')")
    @Log(title = "网元-接口-mtnphy接口", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementPortMtnPhyService.deleteElementPortMtnPhyByIds(ids));
    }
    /**
     * 激活设备
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementPortMtnPhy entity = elementPortMtnPhyService.selectElementPortMtnPhyById(id);
        entity.setStatus("1");
        if (sendXml(entity)){
            return toAjax(elementPortMtnPhyService.updateElementPortMtnPhy(entity));
        }else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementPortMtnPhy entity =  elementPortMtnPhyService.selectElementPortMtnPhyById(id);
        entity.setStatus("0");
        if (sendXml(entity)){
            return toAjax(elementPortMtnPhyService.updateElementPortMtnPhy(entity));
        }else {
            return AjaxResult.error("去激活设备失败");
        }
    }
    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementPortMtnPhy entity) {
        boolean isSend = true;
        if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());
            String xml = "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                    "    <interfaces>" +
                    "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                    "        <name>" + entity.getTerminalName() + "</name>" +
                    "        <type>FLEXE-PHY</type>" +
                    "        <enabled>"+entity.getTerminalEnable()+"</enabled>" +
                    "        <flexe-ctrlinterface xmlns=\"http://fiberhome.com/fhnw/yang/interface/flexeinterface/fos-flexeif-phy\">" +
                    "          <unavailable-timeslot-count>" + entity.getNonAccessNum() + "</unavailable-timeslot-count>" +
//                "          <fec-mode>auto</fec-mode>" +
                    "          <fec-mode>" + entity.getFecMode() + "</fec-mode>" +
                    "          <port-laser-startup-delay-time>0</port-laser-startup-delay-time>" +
                    "          <up-holdtime>200</up-holdtime>" +
                    "          <down-holdtime>0</down-holdtime>" +
                    "          <energy-saving-mode>disable</energy-saving-mode>" +
                    "        </flexe-ctrlinterface>" +
                    "      </interface>" +
                    "    </interfaces>" +
                    "  </if>";
            logger.info("mtnphy激活xml" + xml);
            isSend = deviceManager.editConfig(xml, "merge");
        }
        return isSend;
    }
}